﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
using System.Security.Cryptography;
using System.Text;
using WorkTool2.Classes.Settings;
using WorkTool2.Interfaces;

namespace WorkTool2.Helpers;

public static class SettingsHelper
{
    public static IConfigurationRoot _configurationRoot { get; set; }

    public static FileSettings _fileSettings;

    public static List<CherryPickSettings> _cherryPickSettings;

    public static WorkMonthlyReportSettings _workMonthlyReportSettings;

    public static HolidayStatisticsSettings _holidayStatisticsSettings;

    public static List<CalendarSettings> _calendarSettings;

    private static DateTime _lastConfigChangeTime = DateTime.MinValue;
    private static readonly TimeSpan _debounceInterval = TimeSpan.FromSeconds(1); // 增加防抖间隔
    private static string _lastConfigHash; // 存储配置内容的哈希值

    public static void Init(Form form)
    {
        var basePath = AppDomain.CurrentDomain.BaseDirectory; // 使用固定基路径
        _configurationRoot = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile(path: Path.Combine("Resources", "calendarSettings.json"), optional: true, reloadOnChange: true)
            .AddJsonFile(path: Path.Combine("Resources", "appsettings.json"), optional: false, reloadOnChange: true)
            .Build();

        ChangeSettings();
        _lastConfigHash = ComputeConfigHash(); // 初始化时计算哈希

        ChangeToken.OnChange(
            () => _configurationRoot.GetReloadToken(),
            () =>
            {
                var now = DateTime.Now;
                if (now - _lastConfigChangeTime < _debounceInterval)
                {
                    return;
                }

                // 检查配置内容是否实际发生变化
                string currentHash = ComputeConfigHash();
                if (currentHash == _lastConfigHash)
                {
                    return; // 配置未实际变更，忽略此次通知
                }

                _lastConfigChangeTime = now;
                _lastConfigHash = currentHash;

                ChangeSettings();
                AntdUI.Notification.info(form, "配置文件已更新", "", AntdUI.TAlignFrom.TR);
                var control = (form as Main)?.control_add; // 使用null条件操作符避免异常
                if (control is IReload controlReload)
                {
                    controlReload.Reload();
                }
            }
        );
    }

    /// <summary>
    /// 计算配置内容的哈希值
    /// </summary>
    /// <returns></returns>
    private static string ComputeConfigHash()
    {
        var content = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "appsettings.json"));
        using var sha256 = SHA256.Create();
        byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(content));
        return Convert.ToBase64String(hash);
    }

    /// <summary>
    /// 更新配置
    /// </summary>
    /// <param name="config"></param>
    public static void ChangeSettings()
    {
        var fileSettings = _configurationRoot.GetSection("FileSettings").Get<FileSettings>();
        if (!fileSettings.SaveFolder.Equals(_fileSettings?.SaveFolder))
            fileSettings.SaveFolder = ToolHelper.CreateDirectory(fileSettings.SaveFolder);
        _fileSettings = fileSettings;
        _cherryPickSettings = _configurationRoot.GetSection("CherryPick").Get<List<CherryPickSettings>>();
        _workMonthlyReportSettings = _configurationRoot.GetSection("WorkMonthlyReport").Get<WorkMonthlyReportSettings>();
        _holidayStatisticsSettings = _configurationRoot.GetSection("HolidayStatistics").Get<HolidayStatisticsSettings>();
        _calendarSettings = _configurationRoot.GetSection("CalendarSettings").Get<List<CalendarSettings>>();
    }
}